package com.qfedu.api.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.api.feign.UserCheckClient;
import com.qfedu.api.service.userLoginService;
import com.qfedu.fmmall.beans.Users;
import com.qfedu.fmmall.utils.MD5Utils;
import com.qfedu.fmmall.vo.ResultStatus;
import com.qfedu.fmmall.vo.ResultVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class userLoginServiceImpl implements userLoginService {

    @Autowired
    private UserCheckClient userCheckClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public ResultVo checkLogin(String username, String password) {

        //1.调用user-check服务，根据用户名查询用户信息
        Users user = userCheckClient.check(username);

        //2.校验用户是否存在
        if(user == null){
            return  new ResultVo(ResultStatus.NO,"用户名不存在",null);
        }else{
            String md5Pwd = MD5Utils.md5(password);
            if(md5Pwd.equals(user.getPassword())){

                //如果登录验证成功，则需要生成令牌token (token就是按照特定规则生成的字符串)
                //使用jwt 规则生成token字符串
                JwtBuilder builder = Jwts.builder();

                String token = builder.setSubject(username) //主题，就是token 中携带的数据
                        .setIssuedAt(new Date())     //设置token 的生成时间
                        .setId(user.getUserId() + "")//设置用户id为token  id
                        .setExpiration(new Date(System.currentTimeMillis() + 24*60*60*1000)) //设置过期时间
                        .signWith(SignatureAlgorithm.HS256, "QIANFeng6666") //设置加密方式和加密密码
                        .compact();

                try {
                    String userData = objectMapper.writeValueAsString(user);
                    stringRedisTemplate.boundValueOps(token).set(userData,30, TimeUnit.MINUTES);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }


                return  new ResultVo(ResultStatus.OK,token,user);
            }else{
                return  new ResultVo(ResultStatus.NO,"密码错误",null);
            }
        }

    }
}
